<template>
  <div class="order">
    <!-- 黑色导航栏 -->
    <navTop></navTop>
    <!-- 一级导航栏 -->
    <navTwo class="navTwo"></navTwo>

    <!-- 订单内容 -->
    <main>
      <div class="orderTop">
        <h1>核对订单信息</h1>
      </div>

      <!-- 地址 -->
      <div class="address">
        <h2>收货人信息</h2>
        <div class="add" @click="newAdd">
          <i class="el-icon-edit"></i>新增收货地址
        </div>
        <div class="addressBox">
          <!-- 地址盒子 -->
          <div>
            <table cellspacing="0" cellpadding="20" class="table" width="70%">
              <tr class="THheight">
                <th>收货人</th>
                <th>所在地区</th>
                <th>详细地址</th>
                <!-- <th>邮编</th> -->
                <th>电话/手机</th>
                <th>操作</th>
                <th></th>
              </tr>
              <tr v-for="item in userAddress" :key="item.id" class="Trheight">
                <td>{{ item.name }}</td>
                <td>{{ item.area_name }}</td>
                <td>{{ item.desc }}</td>
                <!-- <td>{{ item.post_code }}</td> -->
                <td>{{ item.phone }}</td>
                <td>
                  <span @click="UpdataAddress(item.id)" class="updata"
                    >修改</span
                  >
                  | <span @click="delAddress(item.id)" class="del">删除</span>
                </td>
                <td @click="defaultAddress(item.id)" class="moren">
                  <p v-show="item.default_set == 1 ? false : true">设为默认</p>
                  <p
                    v-show="item.default_set == 1 ? true : false"
                    class="default"
                  >
                    默认地址
                  </p>
                </td>
              </tr>
            </table>
          </div>
          <!-- 添加新盒子 -->
          <!-- <div class="newBox" @click="newAdd">
            <h3>添加新地址</h3>
          </div> -->

          <!-- 点击弹出的表单填写 -->
          <div
            class="addAddressMask"
            v-show="isShowAddAddress"
            @mousewheel.prevent
            @touchmove.prevent
          >
            <div class="addressContent">
              <div class="title">
                <h3>添加地址</h3>
                <i @click="openAddAddress" class="el-icon-close"></i>
              </div>
              <div class="contentInput">
                <div>
                  <el-input
                    v-model="user.name"
                    placeholder="您的姓名"
                  ></el-input>
                </div>
                <div>
                  <el-input
                    v-model="user.phone"
                    placeholder="手机号"
                  ></el-input>
                </div>
                <div class="block">
                  <el-cascader
                    v-model="user.address"
                    :options="options"
                    placeholder="请选择地址"
                  ></el-cascader>
                </div>
                <div>
                  <el-input
                    v-model="user.addressDatial"
                    placeholder="详细地址"
                  ></el-input>
                </div>
                <div class="dizhi">
                  <label for="dizhi"
                    ><input
                      type="checkbox"
                      name=""
                      id="dizhi"
                      v-model="isChecked"
                    /><span>默认收货地址</span></label
                  >
                </div>
                <p>
                  有关我们如何使用您的个人信息，请参阅我们的<span>隐私政策</span>。
                </p>
                <div>
                  <button @click="isSureAdd">保存</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 购物车内容 -->
      <div class="shopgood">
        <div class="goodTop">
          <h2>确认商品信息</h2>
          <p @click="toCar">返回购物车修改></p>
        </div>
        <div class="goodTable">
          <template>
            <el-table
              ref="multipleTable"
              :data="orderlist"
              tooltip-effect="dark"
              style="width: 100%"
              max-height="500"
            >
              <!-- 商品名称 -->
              <el-table-column
                prop="s_good.name"
                label="商品名称"
                width="250"
                align="center"
              >
              </el-table-column>
              <!-- 商品单价 -->
              <el-table-column
                prop="s_good.price"
                label="价格(元)"
                width="230"
                align="center"
              >
              </el-table-column>
              <!-- 手机配置 -->
              <el-table-column
                prop="subtotal"
                label="配置"
                width="200"
                align="center"
              >
                <template slot-scope="scope">
                  <div v-show="!scope.row.skuName">默认配置</div>
                  <template v-for="(item, index) in scope.row.skuName">
                    {{ item }}:{{ scope.row.skuInfo[index] }}&nbsp;
                  </template>
                </template>
              </el-table-column>
              <!-- 商品数量 -->
              <el-table-column
                prop="num"
                label="数量"
                width="250"
                align="center"
              >
                <!-- <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.num"
                    @change="handleChange(scope.row.num, scope.row.id)"
                    :min="1"
                  ></el-input-number>
                </template> -->
              </el-table-column>
              <!-- 优惠价格 -->
              <!-- <el-table-column
                prop="s_good.sale_price"
                label="优惠"
                width="200"
                align="center"
              >
              </el-table-column> -->
              <!-- 单个商品小计 -->
              <el-table-column
                prop="subtotal"
                label="小计(元)"
                width="200"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row.s_good.price * scope.row.num }}
                </template>
              </el-table-column>
            </el-table>
          </template>
        </div>
      </div>

      <div class="total">
        <div class="numTotal">
          <p>
            已选<span>{{ goodsNumber }}</span
            >件商品，合计（不含运费）:<span>￥{{ goodsSumPrice }}</span
            >元
          </p>
          <p>运费：<span>￥0</span>元</p>
          <!-- <p>
            优惠：<span>￥{{ goodsDis }}</span
            >元
          </p> -->
        </div>
        <div class="shopTotal">
          <p>
            应付总额：<span>￥{{ goodsSumPrice }}元</span>
          </p>
          <p>收件人：{{ userDefName }}</p>
          <p>配送地址：{{ userDefAddress }}</p>
          <button @click="Sub">提交订单</button>
        </div>
      </div>
    </main>

    <!-- 底部 -->
    <bottomList></bottomList>
  </div>
</template>

<script>
import navTop from "../components/navtop";
import navTwo from "../components/navTwo";
import bottomList from "../components/bottomList";
import {
  getAddress,
  addAddress,
  delAddress,
  updataAddress,
  DefaultAddress,
  getDefault,
  shopCarDel,
  setOrder,
  orderpay,
  getAllCity,
} from "../api/test";
export default {
  name: "order",
  components: {
    navTop,
    navTwo,
    bottomList,
  },
  //进来获取用户信息的地址
  async created() {
    //获取用户全部填写的地址
    try {
      let res = await getAddress({});
      this.userAddress = res.data.result;
      //获取用户的默认地址
      let def = await getDefault({});
      console.log(def);
      this.userDefName = def.data.result.name;
      this.userDefAddress = def.data.result.area_name + def.data.result.desc;

      this.userAddress.forEach((item, index) => {
        if (item.default_set === "1") {
          this.userAddress.splice(index, 1);
          this.userAddress.unshift(item);
          console.log(item);
        }
      });
    } catch (error) {
      console.log(error);
    }

    if (sessionStorage.getItem("AllCity")) {
      this.options = JSON.parse(sessionStorage.getItem("AllCity"));
    } else {
      getAllCity().then((res) => {
        res.data.result.forEach((item, index) => {
          this.options.push({
            value: item.label,
            label: item.label,
            children: [],
          });

          item.children.forEach((item2, index2) => {
            this.options[index].children.push({
              value: item2.label,
              label: item2.label,
              children: [],
            });
            if (item2.children) {
              item2.children.forEach((item3, index3) => {
                // console.log(item3.labely);
                this.options[index].children[index2].children.push({
                  value: item3.label,
                  label: item3.label,
                });
              });
            }
          });
        });
        sessionStorage.setItem("AllCity", JSON.stringify(this.options));
      });
    }
  },
  data() {
    return {
      // 地址框状态
      isShowAddAddress: false,
      //用户填写的信息
      user: {
        name: "",
        phone: "",
        address: "",
        addressDatial: "",
      },
      //默认地址的单选框状态
      isChecked: false,
      //地址的集合
      options: [],
      //用户的地址存放
      userAddress: [],
      //保存按钮是修改还是添加的根据
      isBtn: "",
      //保存修改的ID
      isID: "",

      //用户勾选的商品
      orderlist: JSON.parse(sessionStorage.getItem("order")),

      //用户的默认地址信息
      userDefName: "",
      userDefAddress: "",
      flag: true,
    };
  },
  methods: {
    //打开表单填写地址
    newAdd() {
      this.isShowAddAddress = true;
      this.isBtn = "add";
      //清空选择
      this.user.name = "";
      this.user.phone = "";
      this.user.address = "";
      this.user.addressDatial = "";
      this.isChecked = false;
    },
    //关闭弹出的表单
    openAddAddress() {
      this.isShowAddAddress = false;
    },
    //保存按钮添加地址/修改地址
    async isSureAdd() {
      //根据isBtn的状态来判断是添加还是修改
      if (this.isBtn == "add") {
        await addAddress({
          name: this.user.name,
          phone: this.user.phone,
          area: 1,
          area_name: this.user.address.join(" "),
          desc: this.user.addressDatial,
          default_set: this.isChecked == true ? 1 : 0,
        })
          .then((res) => {
            console.log(res);
            this.userAddress.unshift(res.data.result);
            this.isShowAddAddress = false;
            this.$message({
              message: res.data.msg,
              type: "success",
              duration: 1000,
            });
            this.userAddress.forEach((item) => {
              if (item.default_set === "1") {
                item.default_set = 0;
              }
            });
          })
          .catch((err) => {
            this.$message.error({
              message: err.response.data.msg,
              duration: 1500,
            });
          });
      } else if (this.isBtn == "updata") {
        if (this.isChecked) {
          let res2 = await getDefault({});
          console.log(res2.data.result);

          await updataAddress(res2.data.result.id, {
            name: res2.data.result.name,
            phone: res2.data.result.phone,
            area: 1,
            area_name: res2.data.result.address,
            desc: res2.data.result.addressDatial,
            default_set: 0,
          });
        }
        await updataAddress(this.isID, {
          name: this.user.name,
          phone: this.user.phone,
          area: 1,
          area_name: this.user.address.join(" "),
          desc: this.user.addressDatial,
          default_set: this.isChecked == true ? 1 : 0,
        })
          .then(async (res) => {
            this.isShowAddAddress = false;
            this.$message({
              message: "修改成功",
              type: "success",
              duration: 1000,
            });
            // let res2 = await getAddress({});
            // this.userAddress = res2.data.result;
            // let res3 = await getDefault({});
            // let del = this.userAddress.findIndex((item) => {
            //   return item.id == res3.id;
            // });
            // this.userAddress.splice(del, 1);
            // this.userAddress.unshift(res3);
            this.userAddress.forEach((item, index) => {
              if (item.default_set == 1) {
                // item.splice(index, 1);
                this.userAddress.splice(index, 1);
                this.userAddress.unshift(item);
              } else {
                item.default_set = 0;
              }
            });
          })
          .catch((err) => {
            this.$message.error({
              message: "修改失败",
              duration: 1000,
            });
          });
      }
    },
    //删除地址
    delAddress(id) {
      this.$confirm("此操作将删除地址, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await delAddress(id);
          this.$message({
            type: "success",
            message: res.data.msg,
          });
          let newRes = await getAddress({});
          this.userAddress = newRes.data.result;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //修改地址
    async UpdataAddress(id) {
      this.isID = id;
      this.isShowAddAddress = true;
      this.isBtn = "updata";
      await getAddress({}).then(async (res) => {
        //返回要被修改的item
        let arr = await res.data.result.filter((item) => {
          return item.id == id;
        });

        console.log(arr[0].default_set);
        this.user.name = arr[0].name;
        this.user.phone = arr[0].phone;
        this.user.address = arr[0].area_name.split(" ");
        this.user.addressDatial = arr[0].desc;
        this.isChecked = arr[0].default_set == "1" ? true : false;
      });
    },
    //修改默认地址
    async defaultAddress(id) {
      this.$confirm("此操作将修改默认地址, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await DefaultAddress(id);
          this.userAddress.forEach((item, index) => {
            if (item.id == id) {
              item.default_set = 1;
              // item.splice(index, 1);
              this.userAddress.splice(index, 1);
              this.userAddress.unshift(item);
              console.log(item);
            } else {
              item.default_set = 0;
            }
          });
          this.userDefName = res.data.result.name;
          this.userDefAddress =
            res.data.result.area_name + res.data.result.desc;
          this.$message({
            type: "success",
            message: res.data.msg,
          });
          // let newRes = await getAddress({});
          // this.userAddress = newRes.data.result;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //返回购物车修改
    toCar() {
      this.$router.push({ path: "/personal/shopCar" });
    },

    //提交
    Sub() {
      this.$confirm("将提交订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //创造一个数组存放
          let list = [];
          //把goodId和num挑出来存放进数组里
          this.orderlist.forEach((item) => {
            list.push({ id: item.goods_id, num: item.num });
            shopCarDel(item.id);
          });
          await setOrder({
            project_id: 149,
            addr_id: 1,
            goods_info: list,
          })
            .then((res) => {
              console.log(res);
              sessionStorage.setItem(
                "OrderId",
                JSON.stringify(res.data.result)
              );
              this.$router.push({ path: "/payInfo" });
            })
            .catch((err) => {
              console.log(err);
              this.$message({
                type: "info",
                message: "创建失效",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消交易",
          });
        });
    },
  },
  computed: {
    goodsNumber() {
      if (this.orderlist.length !== 0) {
        return this.orderlist.reduce((total, item) => {
          return (total += item.num);
        }, 0);
      } else {
        return 0;
      }
    },
    goodsSumPrice() {
      if (this.orderlist.length !== 0) {
        return this.orderlist.reduce((total, item) => {
          return (total += item.num * item.s_good.price);
        }, 0);
      } else {
        return 0;
      }
    },
    goodsDis() {
      if (this.orderlist.length !== 0) {
        return this.orderlist.reduce((total, item) => {
          return (total += item.s_good.sale_price * item.num);
        }, 0);
      } else {
        return 0;
      }
    },
    goodsPrice() {
      if (this.orderlist.length !== 0) {
        return this.orderlist.reduce((total, item) => {
          return (total +=
            item.num * (item.s_good.price - item.s_good.sale_price));
        }, 0);
      } else {
        return 0;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.order {
  background-color: rgb(247, 247, 247);
}
.navTwo {
  height: 80px;
  position: relative;
}
main {
  margin: 0 auto;
  width: 1200px;
  .orderTop {
    background-color: rgb(255, 255, 255);
    height: 66px;
    line-height: 66px;
    margin-bottom: 19px;
  }
  .address {
    background-color: rgb(255, 255, 255);
    width: 1130px;
    padding: 35px;
    margin-bottom: 19px;
    // height: 202px;
    h2 {
      text-align: left;
    }
    .add {
      width: 150px;
      border: 1px solid gray;
      background-color: red;
      border-radius: 5px;
      margin-left: 170px;
      height: 50px;
      line-height: 50px;
      color: white;
      font-weight: bold;
      margin-top: 50px;
      &:hover {
        cursor: pointer;
      }
    }
    .addressBox {
      // text-align: left;
      // display: flex;
      // flex-wrap: wrap;
      .box {
        width: 269px;
        height: 155px;
        margin: 0px 15px 20px 0px;
        // border: 5px dotted red;
        // background-image: url(../assets/边框.png);

        flex-direction: column;
        justify-content: space-around;
        padding: 15px;
        cursor: pointer;
        .user {
          display: flex;
          justify-content: space-between;
        }
        .operation {
          display: flex;
          justify-content: space-between;
          color: royalblue;
          p:hover {
            color: red;
          }
        }
      }
      .boxBorder {
        background: url(../assets/border.png) no-repeat;
        background-size: 300px 185px;
      }
      .boxBorder2 {
        border: 1px solid #000;
      }
      .newBox {
        width: 269px;
        height: 155px;
        margin: 0px 15px 20px 0px;
        border: 5px solid #000;
        padding: 15px;
        text-align: center;
        line-height: 155px;
        cursor: pointer;
      }

      .addAddressMask {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        left: 0;
        top: 0;
        width: 100vw;
        height: 100vh;
        min-height: 1200px;
        z-index: 1000;
        .addressContent {
          width: 50%;
          min-width: 800px;
          background-color: #fff;
          height: 80vh;
          min-height: 800px;
          margin: 40px auto;
          .title {
            height: 80px;
            line-height: 80px;
            position: relative;
            h3 {
              font-weight: normal;
              font-size: 20px;
              text-align: center;
              border-bottom: 1px solid #eee;
              border-top: 6px solid #b12423;
            }
            i {
              position: absolute;
              right: 20px;
              top: 32px;
              font-size: 26px;
            }
          }
          .contentInput {
            box-sizing: border-box;
            padding: 10% 25%;
            > div {
              margin: 20px 0;
            }
            .xingbie {
              span {
                margin-right: 20px;
              }
              label {
                margin-right: 30px;
              }
              input {
                margin-right: 4px;
              }
            }
            .el-cascader {
              width: 100%;
            }
            #dizhi {
              margin-right: 10px;
              width: 16px;
              height: 16px;
            }
            .dizhi {
              padding-top: 30px;
              label {
                display: flex;
                align-items: center;
                input {
                  display: block;
                }
                span {
                  display: block;
                }
              }
            }
            p {
              span {
                text-decoration: underline;
                cursor: pointer;
              }
            }
            button {
              margin-top: 50px;
              width: 128px;
              height: 34px;
              background-color: #000;
              color: #fff;
              outline: none;
              border: 1px solid #000;
              transition: 0.5s;
              cursor: pointer;
            }
            button:hover {
              background-color: #fff;
              color: #000;
            }
          }
        }
      }
      .table {
        margin: 50px auto;
        .updata {
          &:hover {
            color: red;
            cursor: pointer;
          }
        }
        .del {
          &:hover {
            color: red;
            cursor: pointer;
          }
        }
        .moren {
          &:hover {
            color: red;
            cursor: pointer;
          }
        }
        .Trheight {
          height: 50px;
          td {
            border: 1px solid rgb(226, 224, 224);
          }
          &:hover {
            background-color: rgb(211, 211, 211);
          }
          .default {
            border: 1px solid #ff5000;
            width: 70%;
            margin: 0 auto;
            line-height: 30px;
            border-radius: 5px;
            background-color: #ffd6cc;
            color: #f30;
          }
        }
        .THheight {
          height: 40px;
          background-color: rgb(242, 240, 240);
          th {
            border: 1px solid rgb(226, 224, 224);
            font-weight: 200;
            font-size: 15px;
          }
        }
      }
    }
  }
  .shopgood {
    width: 1130px;
    padding: 35px;
    background-color: rgb(255, 255, 255);
    margin-bottom: 19px;
    .goodTop {
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #eeeeee;
      height: 30px;
      padding-bottom: 35px;
      align-items: center;
      p {
        cursor: pointer;
      }
      p:hover {
        color: #f51200;
      }
    }
  }
  .total {
    background-color: rgb(255, 255, 255);
    width: 1130px;
    padding: 35px;
    margin-bottom: 19px;
    text-align: right;
    .numTotal {
      border-bottom: 1px solid #eeeeee;
    }
    p {
      padding: 10px 0px;
    }
    .shopTotal {
      p:first-of-type {
        font-size: 26px;
        span {
          font-size: 32px;
          color: #f51200;
        }
      }
      button {
        font-size: 18px;
        background-color: #f51200;
        height: 46px;
        line-height: 46px;
        border-radius: 23px;
        display: inline-block;
        color: #fff;
        padding: 0 31px;
        min-width: 170px;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        text-align: center;
        cursor: pointer;
        border: none;
      }
    }
  }
}
</style>
